﻿#region Apache 2.0 License header

//   Copyright 2012 Lesley van Zijl
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. 

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using FavourObjects.Extensions;

namespace FavourObjects
{
    /// <summary>
    /// Validator which is able to check if the interface can be implemented.
    /// </summary>
    public static class FavourInterfaceValidator
    {
        /// <summary>
        /// Validates if the interfaceType can be implemented.
        /// </summary>
        /// <param name="interfaceType">The to be implemented interface.</param>
        /// <param name="targetType">The type which needs to be targetted.</param>
        public static void Validate(Type interfaceType, Type targetType)
        {
            Contract.Requires(interfaceType != null);
            Contract.Requires(targetType != null);

            MemberInfo[] memberList = interfaceType.GetMembers();

            var missingMembers = new List<MemberInfo>(memberList);

            foreach (MemberInfo member in memberList)
            {
                switch (member.MemberType)
                {
                    case MemberTypes.Property:
                        if (targetType.HasProperty(member as PropertyInfo))
                        {
                            String propertyName = member.Name;

                            RemovePropertySetter(missingMembers, propertyName);
                            RemovePropertyGetter(missingMembers, propertyName);

                            missingMembers.Remove(member);
                        }
                        else if (targetType.HasField(member.Name))
                        {
                            String propertyName = member.Name;

                            RemovePropertySetter(missingMembers, propertyName);
                            RemovePropertyGetter(missingMembers, propertyName);

                            missingMembers.Remove(member);
                        }
                        break;
                    case MemberTypes.Method:
                        if (targetType.HasMethod(member as MethodInfo))
                        {
                            missingMembers.Remove(member);
                        }
                        break;
                }
            }

            if (missingMembers.Any())
            {
                throw CreateValidationException(missingMembers);
            }
        }

        /// <summary>
        /// Helper method that creates and fills an instance of the validation exception class..
        /// </summary>
        /// <param name="missingMembers">The members that are missing on the target class.</param>
        /// <returns>An instance of a validation exception.</returns>
        private static ValidationException CreateValidationException(List<MemberInfo> missingMembers)
        {
            String message = "Validation Failed, the following methods where not found on the target: ";
            message += String.Join(", ", missingMembers.Select(item => item.ToString()));
            
            var exception = new ValidationException(message);
            exception.SetMissingMembers(missingMembers);
            
            return exception;
        }

        /// <summary>
        /// Helper method that removes a property setter method from a list if it's found in the list.
        /// </summary>
        /// <param name="missingMembers">The list from which the setter will be removed.</param>
        /// <param name="propertyName">The name of the property from which the setter name can be extracted.</param>
        private static void RemovePropertySetter(ICollection<MemberInfo> missingMembers, String propertyName)
        {
            string targetName = "set_" + propertyName;

            MemberInfo setter = missingMembers.FirstOrDefault(item => item.Name == targetName);

            if (setter != null)
            {
                missingMembers.Remove(setter);
            }
        }

        /// <summary>
        /// Helper method that removes a property getter method from a list if it's found in the list.
        /// </summary>
        /// <param name="missingMembers">The list from which the getter will be removed.</param>
        /// <param name="propertyName">The name of the property from which the getter name can be extracted.</param>
        private static void RemovePropertyGetter(ICollection<MemberInfo> missingMembers, String propertyName)
        {
            string targetName = "get_" + propertyName;

            MemberInfo getter = missingMembers.FirstOrDefault(item => item.Name == targetName);

            if (getter != null)
            {
                missingMembers.Remove(getter);
            }
        }
    }
}